use std::cmp::min;

const MAN: [i32; 3] = [4, 1965, 36];
const WOMEN55: [i32; 3] = [4, 1970, 36];
const WOMEN50: [i32; 3] = [2, 1975, 60];
const MONTH_PER_YEAR: i32 = 12;

fn delay(tp: [i32; 3], year: i32, month: i32) -> i32 {
    let mut year = year;
    let mut month = month;
    let mut del = 0;
    if year < tp[1] {
        return 0;
    }
    while year > tp[1] {
        year -= 1;
        del += MONTH_PER_YEAR / tp[0];
    }
    while month >= 1 {
        month -= tp[0];
        del += 1;
    }
    min(del, tp[2])
}

fn add_months(tp: &str, year: i32, month: i32) -> (i32, i32) {
    if tp == "男职工" {
        let del = delay(MAN, year, month);
        (60 * MONTH_PER_YEAR + del, del)
    } else if tp == "原法定退休年龄55周岁女职工" {
        let del = delay(WOMEN55, year, month);
        (55 * MONTH_PER_YEAR + del, del)
    } else if tp == "原法定退休年龄50周岁女职工" {
        let del = delay(WOMEN50, year, month);
        (50 * MONTH_PER_YEAR + del, del)
    } else {
        (0, 0)
    }
}

fn calc_time(year: i32, month: i32, work: i32) -> String {
    let mut year = year + work / MONTH_PER_YEAR;
    let mut month = month + work % MONTH_PER_YEAR;
    if month > MONTH_PER_YEAR {
        month -= MONTH_PER_YEAR;
        year += 1;
    }
    format!("{:04}-{:02}", year, month)
}

pub fn retire_time(time: &str, tp: &str) -> String {
    let year = time[0..4].parse::<i32>().unwrap();
    let month = time[5..7].parse::<i32>().unwrap();
    let (work_month, del) = add_months(tp, year, month);
    let time = calc_time(year, month, work_month);
    let retire_year = work_month as f64 / MONTH_PER_YEAR as f64;
    if work_month % MONTH_PER_YEAR == 0 {
        return format!("{},{:.0},{}", time, retire_year, del);
    }
    format!("{},{:.2},{}", time, retire_year, del)
}
